package tianrun.ziguan.api.calculate.config.service.common.edit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.util.Assert;
import org.springframework.stereotype.Service;
import tianrun.ziguan.api.calculate.config.dto.request.common.DeleteBody;
import tianrun.ziguan.api.calculate.config.dto.request.common.add.edit.SaveBody;
import tianrun.ziguan.api.calculate.config.entity.TTemplate;
import tianrun.ziguan.api.calculate.config.entity.TTemplateGroup;
import tianrun.ziguan.api.calculate.config.service.ge.TGeTableConfigService;
import tianrun.ziguan.api.calculate.config.service.template.ITTemplateService;
import tianrun.ziguan.api.calculate.config.service.template.group.ITTemplateGroupService;
import tianrun.ziguan.api.calculate.config.utils.MapUtil;
import tianrun.ziguan.api.calculate.config.utils.StringUtil;
import tianrun.ziguan.api.common.util.ListUtil;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TemplateGroupDealService extends AbstractDealService implements DealService {

    private final ITTemplateGroupService templateGroupService;
    private final ITTemplateService templateService;

    public TemplateGroupDealService(TGeTableConfigService tableConfigService, ITTemplateGroupService templateGroupService, ITTemplateService templateService) {
        super(tableConfigService);
        this.templateGroupService = templateGroupService;
        this.templateService = templateService;
    }

    @Override
    public void before(SaveBody body) {
        String name = MapUtil.getString(body.getData(), "name");
        if (StringUtil.isEmpty(name))return;
        LambdaQueryWrapper<TTemplateGroup> wrapper = Wrappers.<TTemplateGroup>lambdaQuery().eq(TTemplateGroup::getIsValid, true).eq(TTemplateGroup::getName, name);
        if (Objects.equals(body.getOption(), SaveBody.Option.EDIT)) {
            wrapper.ne(TTemplateGroup::getId, body.getId());
        }
        int count = templateGroupService.count(wrapper);
        // todo
        Assert.isTrue(count == 0, name + "已存在！");
    }

    @Override
    public String tableName() {
        return "t_template_group";
    }

    @Override
    public void after(SaveBody body) {

    }

    @Override
    public void delBefore(DeleteBody body) {
        //todo 删除校验,有模板的不能删
        List<TTemplate> templates = templateService.queryListByGroupId(body.getIds());
        Assert.isTrue(ListUtil.isEmpty(templates), getDelErrorMessage(templates));
    }

    @Override
    public void listAfter(List<Map<String, Object>> result) {

    }

    @Override
    public void delAfter(DeleteBody body) {

    }

    @Override
    public void infoAfter(Map<String, Object> bean) {

    }

    private String getDelErrorMessage(List<TTemplate> templates) {
        StringBuffer sb = new StringBuffer();
        List<Long> templateGroupIds = templates.stream().map(TTemplate::getTemplateGroupId).collect(Collectors.toList());
        if (ListUtil.isEmpty(templateGroupIds))return "";
        Collection<TTemplateGroup> tTemplateGroups = templateGroupService.listByIds(templateGroupIds);
        tTemplateGroups.stream().forEach(templateGroup -> {
            sb.append(templateGroup.getName())
                    .append(" 下包含模板（")
                    .append(templates.stream().filter(t->Objects.equals(t.getTemplateGroupId(),templateGroup.getId())).count())
                    .append("个）：");
            templates.stream()
                    .filter(t->Objects.equals(t.getTemplateGroupId(),templateGroup.getId()))
                    .forEach(t->sb.append(t.getName()).append("、"));
            sb.deleteCharAt(sb.length()-1).append("。\n");
        });
        return sb.deleteCharAt(sb.length()-1).toString();
    }
}
